// eslint-disable-next-line import/named
import { MutationTree } from 'vuex'
import { ToolStateInterface } from './state'

const mutation: MutationTree<ToolStateInterface> = {
  setTagList (state, payload) {
    state.tag.list = payload
    state.tag.isLoaded = true
  },
  setToolList (state, payload) {
    state.tool.list = payload
  },
  pushToolLike (state, tool) {
    const id = tool._id
    tool.statistics.likeCount++
    state.toolLike.push(id)
  },
  popToolLike (state, tool) {
    const id = tool._id
    tool.statistics.likeCount--
    state.toolLike.splice(id, 1)
  },
  pushToolCollection (state, tool) {
    const id = tool._id
    tool.statistics.collectionCount++
    state.toolCollection.push(id)
  },
  deleteToolCollection (state, tool) {
    const id = tool._id
    tool.statistics.collectionCount--
    state.toolCollection = state.toolCollection.filter(e => e !== id)
  },
  setCurrentTool (state, payload) {
    state.currentTool = {
      ...payload,
      isLike: false,
      isCollection: false
    }
  },
  syncToolWithUser (state, payload: {
    toolLike: string[],
    toolCollection: string[],
  }) {
    const {
      toolLike,
      toolCollection
    } = payload || {}
    if (toolLike) {
      state.toolLike = toolLike
    }
    if (toolCollection) {
      state.toolCollection = toolCollection
    }
    const list = [...state.tool.list]
    if (state.currentTool) {
      list.push(state.currentTool)
    }
    // console.log('state.currentTool', state.currentTool)
    // console.log('state.toolLike', state.toolLike)
    // console.log(list)
    list.forEach(e => {
      e.isLike = !!state.toolLike.find(id => id === e._id)
      e.isCollection = !!state.toolCollection.find(id => id === e._id)
      return e
    })
    // console.log(list)
  }
}
export default mutation
